package com.example.dmweb.chat.chatService.utils;

import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.core.http.HttpConfig;
import com.huaweicloud.sdk.ocr.v1.region.OcrRegion;
import com.huaweicloud.sdk.ocr.v1.*;
import com.huaweicloud.sdk.ocr.v1.model.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Base64;

@Slf4j
public class HWOcrUtil {
    private static String ak = "NXTYZRLZKI85ACEY73MJ";
    private static String sk = "ot5j1WGn8KcmZWJa1q9WVr7iJfR5FqF9FylI7rso";

    public String pic2String(InputStream fileStream,String fileType) {
        Excel2Txt excel2Txt = new Excel2Txt();
        StringBuilder content = new StringBuilder();

        if (fileType.equals("pdf")) {
            excel2Txt.pdf2Pic(fileStream).forEach(v -> {
                try {
                    content.append(excel2Txt.excel2txt(hwOcr(v)));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        } else if (fileType.equals("img")) {
            try {
                content.append(excel2Txt.excel2txt(hwOcr(pictobyte(fileStream))));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        log.info("内容提取完成:{}",content);
        return String.valueOf(content);
    }
    public static String pictobyte(InputStream inputStream) throws IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int nRead;
        byte[] data = new byte[1024];

        while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }

        return Base64.getEncoder().encodeToString(buffer.toByteArray());
    }
    public InputStream hwOcr(String imageBase64) {
        ICredential auth = new BasicCredentials()
                .withAk(ak)
                .withSk(sk);
        HttpConfig httpConfig = HttpConfig.getDefaultHttpConfig();
        OcrClient client = OcrClient.newBuilder()
                .withCredential(auth)
                .withRegion(OcrRegion.valueOf("cn-north-4"))
                .withHttpConfig(httpConfig.withIgnoreSSLVerification(true))
                .build();
        RecognizeGeneralTableRequest request = new RecognizeGeneralTableRequest();
        GeneralTableRequestBody body = new GeneralTableRequestBody();
        body.withReturnExcel(true);
        try {
            // 读取图片文件并进行编码
            body.withImage(imageBase64); // 将编码后的图片数据设置到请求体中
            body.withReturnExcel(true);
            request.withBody(body);
            RecognizeGeneralTableResponse response = client.recognizeGeneralTable(request);
            log.info("华为ocr提取完成:{}"+request);
            String excelBase64 = response.getResult().getExcel(); // 获取响应中的 Excel 数据

            return decodeBase64ToExcel(excelBase64);
        } catch (ConnectionException e) {
            e.printStackTrace();
        } catch (RequestTimeoutException e) {
            e.printStackTrace();
        } catch (ServiceResponseException e) {
            e.printStackTrace();
            log.info("华为报错：{}",e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String encodeImageToBase64(String imagePath) throws IOException {
        File file = new File(imagePath);
        FileInputStream fis = new FileInputStream(file);
        byte[] bytes = new byte[(int) file.length()];
        fis.read(bytes);
        fis.close();
        return Base64.getEncoder().encodeToString(bytes);
    }
    private static String encodeImageToBase64(MultipartFile file) throws IOException {
        // 读取MultipartFile中的字节流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        outputStream.write(file.getBytes());
        byte[] byteArray = outputStream.toByteArray();
        outputStream.close();
        return Base64.getEncoder().encodeToString(byteArray);
    }
    private static void decodeBase64ToExcel(String excelBase64, String outputFilePath) throws IOException {
        byte[] excelBytes = Base64.getDecoder().decode(excelBase64);
        FileUtils.writeByteArrayToFile(new File(outputFilePath), excelBytes);
    }
    private static InputStream decodeBase64ToExcel(String excelBase64) throws IOException {
        byte[] excelBytes = Base64.getDecoder().decode(excelBase64);
        return new ByteArrayInputStream(excelBytes);
    }
}
